package com.example.demo.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Activity;
import com.example.demo.entity.Appointment;
import com.example.demo.entity.AppointmentSign;
import com.example.demo.mapper.AppointmentMapper;
import com.example.demo.mapper.AppointmentSignMapper;
import com.example.demo.service.IAppointmentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @descreption:
 * @author: xhr
 * @date: 2022/08/18
 */
@RestController
@RequestMapping("/appointment")
public class AppointmentController {
    @Resource
    AppointmentMapper appointmentMapper;
    @Resource
    IAppointmentService appointmentService;
    @Resource
    AppointmentSignMapper appointmentSignMapper;

    //增
    @PostMapping
    public Result<?> save(@RequestBody Appointment appointment) {
        appointmentMapper.insert(appointment);
        return Result.success();
    }

    // 改
    @PutMapping
    public Result<?> update(@RequestBody Appointment appointment) {
        appointmentMapper.updateById(appointment);
        return Result.success();
    }

    // 删
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        appointmentMapper.deleteById(id);
        return Result.success();
    }

//    //老师看自己的预约
//    @GetMapping("/teacherPage/{tid}")
//    public Result<?> findTeachers(@PathVariable("tid") Integer tid) {
//        return Result.success(
//                appointmentMapper.selectList(new QueryWrapper<Appointment>().eq("counselor_id", tid))
//        );
//    }

    //全查
    @GetMapping
    public Result<?> findAll() {
        return Result.success(
                appointmentMapper.selectList(null)
        );
    }

    //查
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "10") Integer pagesize,
                              @RequestParam(defaultValue = "1") Integer pagenum,
                              @RequestParam(defaultValue = "") String search,
                              @RequestParam(defaultValue = "1") Integer role,
                              @RequestParam(defaultValue = "") Integer id) {
        LambdaQueryWrapper<Appointment> wrapper;
        if (role == 1) {
            wrapper = Wrappers.<Appointment>lambdaQuery();
        } else {
            wrapper = Wrappers.<Appointment>lambdaQuery().eq(Appointment::getCounselorId, id);
        }
//        LambdaQueryWrapper<Appointment> wrapper = Wrappers.<Appointment>lambdaQuery().eq(Appointment::getCounselorId,role);
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Appointment::getRoom, search);
        }
        return Result.success(appointmentMapper.selectPage(new Page<>(pagenum, pagesize), wrapper));
    }

    //学生小程序显示预约和控制当天的预约数量
    @GetMapping("/page/front")
    public Result<?> enableExam() {
        List<Appointment> appointmentList = appointmentService.list();
        //当天的预约数量

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        List<AppointmentSign> appointmentSignList = appointmentSignMapper.selectList(new QueryWrapper<AppointmentSign>().eq("time", formatter.format(new Date())));
        for (Appointment appointment : appointmentList) {
            appointment.setSurplus(appointment.getLimitPeople());
            Integer appointmentId = appointment.getId();
            appointmentSignList.stream().filter(sign -> sign.getAppointmentId().equals(appointmentId)).collect(Collectors.toList()).forEach(sign -> {
                if (appointment.getSurplus() > 0) {
                    appointment.setSurplus(appointment.getSurplus() - 1);
                }
            });
            setState(appointment);
        }

        return Result.success(appointmentList);
    }

    private void setState(Appointment appointment) {
        String dateTime = appointment.getTime();
        String dateTime1 = dateTime.split("——")[0];
        String dateTime2 = dateTime.split("——")[1];
        DateTime DllTime1 = DateUtil.parse(dateTime1, "yyyy-MM-dd");
        DateTime DllTime2 = DateUtil.parse(dateTime2, "yyyy-MM-dd");
        Date now = new Date();
        if (DateUtil.compare(now, DllTime1) < 0) {
            appointment.setState("未开始");
        } else if (DateUtil.compare(now, DllTime2) < 0) {
            appointment.setState("进行中");
        } else {
            appointment.setState("已结束");
        }

    }
}
